#include "tcpclientform.h"
#include "ui_tcpclientform.h"
#include <QHostAddress>


TcpClientForm::TcpClientForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::TcpClientForm)
    , m_socket(nullptr)
{
    ui->setupUi(this);

    ui->lineEdit_local_ip->setEnabled(false);
    ui->lineEdit_local_port->setEnabled(false);

    connect(ui->pushButton_connect, &QPushButton::clicked, this, &TcpClientForm::slot_connect);
    connect(ui->pushButton_disconnect, &QPushButton::clicked, this, &TcpClientForm::slot_disconnect);
}

TcpClientForm::~TcpClientForm()
{
    delete ui;
}


void TcpClientForm::Send(const stParameter& parameter)
{
    if(m_socket && m_socket->isOpen() && m_socket->isValid()){
        m_socket->write(parameter.Array);
    }
}

#include <QMessageBox>
void TcpClientForm::slot_connect()
{
    if(nullptr == this->m_socket){
        m_socket = new QTcpSocket(this);

        connect(this->m_socket, &QTcpSocket::connected, this, [=](){
            ui->lineEdit_local_ip->setText(this->m_socket->localAddress().toString());
            ui->lineEdit_local_port->setText(QString::number(this->m_socket->localPort()));
        });

        connect(m_socket,&QTcpSocket::readyRead,[=](){
            //没有可读的数据就返回
            if(m_socket->bytesAvailable()<=0)
                return;
            //注意收发两端文本要使用对应的编解码
            QByteArray array = m_socket->readAll();

            emit this->SigData(array);
        });

        //判断当前是否已连接，连接了就断开
        if(m_socket->state()==QAbstractSocket::ConnectedState){
            //如果使用disconnectFromHost()不会重置套接字，isValid还是会为true
            m_socket->abort();
        }else if(m_socket->state()==QAbstractSocket::UnconnectedState){
            //从界面上读取ip和端口
            const QHostAddress address=QHostAddress(ui->lineEdit_remote_ip->text());
            const unsigned short port=ui->lineEdit_remote_port->text().toUShort();
            //连接服务器
            m_socket->connectToHost(address,port);
            if(m_socket->isValid()){
                QMessageBox msgBox;
                msgBox.setText("连接成功");
                msgBox.setInformativeText("提示");
                msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
                msgBox.exec();
            }
        }else{
            QMessageBox msgBox;
            msgBox.setText("连接失败");
            msgBox.setInformativeText("提示");
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
            msgBox.exec();
        }
    }
}


void TcpClientForm::slot_disconnect()
{
    if(m_socket && m_socket->isOpen() && m_socket->isValid()){
        m_socket->close();
        QMessageBox msgBox;
        msgBox.setText("连接已断开");
        msgBox.setInformativeText("提示");
        msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
        msgBox.exec();
    }
}


